package com.start.common.tools;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class StartTools {
    /**
     * 合并JSON对象，用source覆盖target，返回覆盖后的JSON对象，
     *
     * @param source JSONObject
     * @param target JSONObject
     * @return JSONObject
     */
    public static JSONObject jsonMerge(JSONObject source, JSONObject target) {
        // 覆盖目标JSON为空，直接返回覆盖源
        if (target == null) {
            return source;
        }

        for (String key : source.keySet()) {
            Object value = source.get(key);
            if (!target.containsKey(key)) {
                target.put(key, value);
                continue;
            }
            if (value instanceof JSONObject) {
                JSONObject valueJson = (JSONObject) value;
                JSONObject targetValue = jsonMerge(valueJson, target.getJSONObject(key));
                target.put(key, targetValue);
            } else if (value instanceof JSONArray) {
                JSONArray valueArray = (JSONArray) value;
                for (int i = 0; i < valueArray.size(); i++) {
                    JSONObject obj = (JSONObject) valueArray.get(i);
                    JSONObject targetValue = jsonMerge(obj, (JSONObject) target.getJSONArray(key).get(i));
                    target.getJSONArray(key).set(i, targetValue);
                }
            } else {
                target.put(key, value);
            }
        }
        return target;
    }

    public static List<String> strToList(String data, String split) {
        if (data.contains(split)) {
            return Arrays.stream(data.split(split)).distinct().collect(Collectors.toList());
        }
        List<String> result = new ArrayList<>();
        result.add(data);
        return result;
    }
}
